<?php
 /**
 * class WeixinAction 处理微信接口的请求
 * @created on 2014/1/10
 * @last updated 2015/02/4 
 * @author yanqizheng
 */
namespace Api\Controller;
use Think\Controller;
use Spark\Util\HttpClient;

class WeixinController extends Controller {
    private $wx;
    private $xmlArr;
    private $responsestype = false;
	public function index(){
        $echoStr = $_GET["echostr"];
        if($echoStr){
            file_put_contents("WeixinController.txt",$_SERVER["QUERY_STRING"],FILE_APPEND);
            file_put_contents("WeixinController.txt","\n",FILE_APPEND);
            file_put_contents("WeixinController.txt",$echoStr,FILE_APPEND);
            file_put_contents("WeixinController.txt","\n",FILE_APPEND);
        	echo $echoStr;
        }else{
        	$this->xmlHandle();
        }
        exit();  
    }
    public function show_user(){ 
        $parentInfo = M('juejin_users')->select();
        foreach ($parentInfo as $info) {
            var_dump($info);
            echo '</br></br>';
        }
    }
    public function del_user(){ 
        $id = $_GET['userid'] ? $_GET['userid'] : '';
        if($id){
            $parentInfo = M('juejin_users')->where(['id'=>$id])->delete();
            var_dump($parentInfo);
        }
    }
    private function xmlHandle(){  
		$this->getXMLInfo();
        if ($this->xmlArr){
            $this->wx = M('wxuser')->where(['wxid'=>$this->xmlArr['ToUserName']])->find();
            if($this->wx){
            	if($this->xmlArr['MsgType'] == 'text'){
	            	$this->textHandle(); 
	            }else if($this->xmlArr['MsgType'] == 'event'){
	            	$this->eventHandle(); 
	            }else{
	            	$this->defaultResponse();
	            }  
            }  
        }
        
        if($this->responsestype==false){
        	$this->noResponse();
	    }
    }
    private function getXMLInfo(){
		ob_clean();
        $xmlStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if(!empty($xmlStr)){
	    	$this->xmlArr = json_decode(json_encode(simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA)),TRUE);
	    	$this->xmlArr['Time'] = time();
        }else{
        	return false;
        }
    }
    private function textHandle(){
    	$content = trim($this->xmlArr['Content']);
    	//获取关键词消息
        $keywords = M('keyword')->where(['token'=>$this->wx['token']])->select();
        foreach($keywords as $info){
        	if($this->responsestype==false){
        		if($info['is_strict']==1){
        			$inKeyword = $info['keyword']==$content ? true : false;
        		}else{
        			$inKeyword = strstr($content,$info['keyword']) ? true : false;
        		}
        		if($inKeyword){
        			if($info['module']=='Img'){	
						$this->imgResponse($info);
        			}
        			if($info['module']=='Text'){
						$this->textResponse($info);
        			}
        		}
        	}
	    }
	    //回复默认消息
	    if($this->responsestype==false){
	    	$this->defaultResponse();
	    }
    }

    /*事件处理*/
    private function eventHandle(){
        $Event = $this->xmlArr['Event'];
        /*订阅的时候，去数据库中查找openid*/
        if($Event == 'subscribe'){
            $EventKey = $this->xmlArr['EventKey'];
            M('wxuser')->field('wxfans')->where(['token'=>$this->wx['token']])->setInc('wxfans');
            $this->getSubscribeInfo();
            if(!empty($EventKey)){
                $EventKey = str_replace("qrscene_","",$EventKey);
                $this->updateUserInfo($EventKey);
                $this->areplyResponse();
            }else{
        		$this->areplyResponse();
            }  
        }elseif ($Event == 'unsubscribe'){  
            M('wxuser')->field('wxfans')->where(['token'=>$this->wx['token']])->setDec('wxfans');
        	$this->noResponse();
        }elseif($Event == 'SCAN' || $Event == 'scan'){  
            $EventKey = $this->xmlArr['EventKey'];
            $Ticket = $this->xmlArr['Ticket'];
            $this->updateUserInfo($EventKey);
            $this->noResponse();
        }else{  
        	$this->noResponse();
        }  
    }
    private function getSubscribeInfo(){
        $util = new \Spark\Wechat\WechatUtil($this->wx['appid'],$this->wx['appsecret']);
        $userinfo = $util->getUser($this->xmlArr['FromUserName']);
        $data['token'] =$this->wx['token'];
        $data['open_id'] = $this->xmlArr['FromUserName'];
        $data['wechat_name'] = $userinfo->nickname;
        $data['sex'] = $userinfo->sex;
        $data['language'] = $userinfo->language;
        $data['country'] = $userinfo->country;
        $data['province'] = $userinfo->province;
        $data['headimgurl'] = substr($userinfo->headimgurl,0,-1);
        $data['subscribe_time'] = $userinfo->subscribe_time;
        $data['subscribe'] = $userinfo->subscribe;
        $data['update_time'] = time();
        $isUserCreate = M('wechat_user')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        if($isUserCreate){
            M('wechat_user')->where(['open_id'=>$this->xmlArr['FromUserName']])->save($data);
        }else{
            M('wechat_user')->add($data);
        }
    }


    private function updateUserInfo($parentid){
        /*添加或者更新用户信息时
        1、检查是否有shareid。2、检查是否是旧用户*/
        $parentInfo = M('juejin_users')->where(['id'=>$parentid])->find();
        $token = "";
        $parentid = "";
        $dateary = "";

        if($parentInfo){
           $token = $parentInfo['token'];
           $parentid = $parentInfo['id'];
        }


        /*2.检查是否是旧用户*/
        $userinfo = M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        $wechatuser = M('wechat_user')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
        if( $userinfo )
        {
            /*update updatetime,*/

        }else{
            /*add */
            $dateary['open_id'] = $this->xmlArr['FromUserName'];
            $dateary['create_time'] = time();
            $dateary['last_login_time'] = "";
            $dateary['last_login_ip'] = "";
            $dateary['shareid'] = $parentid;
            $dateary['headimgurl'] = $wechatuser['headimgurl'];
            M('juejin_users')->add( $dateary );
        }

    }

    private function imgResponse($info){
        $resContent = M('Img')->where(['id'=>$info['pid']])->find();
		$resContent['url'] = $resContent['url']=='' ? $resContent['info'] : $resContent['url'];
		$resultStr = sprintf($this->newsTpl,$this->xmlArr['FromUserName'],$this->xmlArr['ToUserName'],$this->xmlArr['Time'],'news',1,
			$resContent['title'],$resContent['text'],$resContent['pic'],$resContent['url']);  
		echo $resultStr; 	
        $this->responsestype=true;
    }
    private function textResponse($info){
        $resContent = M('Text')->where(['id'=>$info['pid']])->find();
        $resultStr = sprintf($this->textTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'text', $resContent['text']); 
		echo $resultStr; 	
        $this->responsestype=true;
    }
    private function defaultResponse(){
        $resContent = M('other')->where(['token'=>$this->wx['token']])->find();
	    $resultStr = sprintf($this->textTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'text', $resContent['keyword']); 
	    echo $resultStr;  
        $this->responsestype=true;
    }
    /*关注回复*/
    private function areplyResponse(){
    	$idindex = 0;
    	$userinfo = M('juejin_users')->where(['open_id'=>$this->xmlArr['FromUserName']])->find();
    	$wechatUser = M('wechat_user')->where(['open_id'=>$this->xmlArr['FromUserName']])->field('wechat_name')->find();
    	$in='终于等到你'.$wechatUser['wechat_name'].'！你是第'.$userinfo['id'].'位发现我们的智者！<br/>本次积分兑换活动是【完全免费，全国包邮】，您无需支付任何费用！获取积分途径：1、点击菜单栏--我的邀请码。2、保存海报分享朋友圈，邀请好友识码关注，成功邀请一位获得1积分，累计38分点击兑换！3、兑换后填写收货人电话和地址，在七个工作日内我们将发货给您！';
	    $resultStr = sprintf($this->textTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'text', $resContent['keyword']); 
	    echo $resultStr;  
        $this->responsestype=true;
    }
    private function msgResponse($msg){
        $resultStr = sprintf($this->textTpl, $this->xmlArr['FromUserName'], $this->xmlArr['ToUserName'], $this->xmlArr['Time'], 'text', $msg); 
        echo $resultStr;  
        $this->responsestype=true;
    }
    private function noResponse(){
        echo 'success';
        $this->responsestype=true;
    }

    private function getWechatUserInfo($openid){
        if(empty($openid)){
            return false;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$this->_accessToken}&openid={$openid}&lang=zh_CN";
        $ret = json_decode(HttpClient::curlGet($url));
        return $ret;
    }

    private $textTpl = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName> 
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>
		</xml>";
	private $newsTpl = "<xml>  
	        <ToUserName><![CDATA[%s]]></ToUserName>  
	        <FromUserName><![CDATA[%s]]></FromUserName>  
	        <CreateTime>%s</CreateTime>  
	        <MsgType><![CDATA[%s]]></MsgType>  
	        <ArticleCount>%s</ArticleCount>  
	        <Articles>
		        <item>  
		        <Title><![CDATA[%s]]></Title>   
		        <Description><![CDATA[%s]]></Description>  
		        <PicUrl><![CDATA[%s]]></PicUrl>  
		        <Url><![CDATA[%s]]></Url>  
		        </item>  
	        </Articles>  
        </xml>";

}
?>